using NLog.Extensions.Logging;
using SmartideRepoList.Models;
using SmartideRepoList.Models.DTO;
using SqlSugar;
using System.Text.Json;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// Add SqlSugar to the services
var client = new SqlSugar.SqlSugarScope(new SqlSugar.ConnectionConfig
{
    DbType = SqlSugar.DbType.SqlServer,
    ConnectionString = builder.Configuration.GetSection("ConnectionString:Default").Value,
    IsAutoCloseConnection = true
});
builder.Services.AddSingleton<ISqlSugarClient>(client);
// Add NLog to the logging
builder.Host.ConfigureLogging(log =>
{
    log.ClearProviders();
#if DEBUG
    log.AddConsole();
#endif
    log.AddNLog("Nlog.config");
});

// Initialize the data
try
{
    //clear data
    client.Ado.ExecuteCommand(@"truncate table TableLeft;truncate table TableRight");
    //get and insert data
    var json = new SmartideRepoList.Utils.ApiUtil().GetProjects(builder.Configuration).Result;
    var data = JsonSerializer.Deserialize<Model[]>(json);
    if (data is not null)
    {
        List<TableLeft> lefts = new List<TableLeft>();
        foreach (var item in data)
        {
            var l = new TableLeft()
            {
                Id = Guid.NewGuid(),
                Name = item.name
            };
            lefts.Add(l);
        }
        client.Insertable<TableLeft>(lefts).ExecuteCommand();
    }
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}


var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.UseCors(options =>
{
    options.AllowAnyHeader();
    options.AllowAnyMethod();
    options.WithOrigins(builder.Configuration.GetSection("CrossDomain").Value, "http://127.0.0.1:5775");
    options.AllowCredentials();
});

app.Run();
